import axios from 'axios'
import {baseUrl} from '@/config/index'

export const getTemp = async () => {
  let data
  await axios.get(`${baseUrl}/assessment/getTemp`).then((response) => {
    data = response.data
  }).catch((error) => {
    console.log(error)
  })

  return data
}

export const getUsers = async () => {
  let data
  axios.get(`${baseUrl}/api/v1/user/allUsers`).then((response) => {
    data = response.data.data
  }).catch((error) => {
    console.log(error)
  })
  return data
}

export const setTemp = async (temp) => {
  let params = new URLSearchParams()
  params.append('partId', temp.partId)
  params.append('itemId', temp.itemId)
  params.append('content', temp.content)
  await axios.post(`${baseUrl}/assessment/setTemp`, params).then((response) => {
    console.log('set', response)
    window.location.href = `${baseUrl}/editor`
  }).catch((error) => {
    console.log(error)
  })
}

export const getAssessment = async (id) => {
  let assessment
  await axios.get(`${baseUrl}/assessment/getOne`, {params: {id}}).then((response) => {
    assessment = response.data
    let parts = sortByIdAsc(assessment.parts)
    for (let i = 0; i < parts.length; i++) {
      let items = sortByIdAsc(parts[i].items)
      parts[i].items = items
    }
    assessment.parts = parts
  }).catch((error) => {
    console.log(error)
  })

  return assessment
}

export const sortByIdAsc = (arrays) => {
  for (let i = 0; i < arrays.length; i++) {
    for (let j = 0; j < arrays.length - i - 1; j++) {
      if (arrays[j].id > arrays[j + 1].id) {
        let temp = arrays[j + 1]
        arrays[j + 1] = arrays[j]
        arrays[j] = temp
      }
    }
  }
  return arrays
}
